<template>
  <div class="user-list-page">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>商户户管理</h1>
      <el-button type="primary" @click="dialogFormVisible = true" :icon="Plus">
        商户用户
      </el-button>
    </div>
    <el-dialog v-model="dialogFormVisible" title="添加商户账号" width="500">
      <el-form :model="form">
        <el-form-item label="商户账号" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商户密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商家名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消添加</el-button>
          <el-button type="primary" @click="handleAddUser">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 筛选和搜索区 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
              v-model="searchForm.keyword"
              placeholder="搜索商户户名/邮箱/手机号"
              prefix-icon="Search"
              @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="正常" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <div class="filter-actions">
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
            <el-button type="warning" @click="handleBatchOperation('export')" v-if="selectedRows.length > 0">
              导出选中
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 商户户列表 -->
    <el-card class="user-table-card">
      <div class="table-actions">
        <el-checkbox
            v-model="selectAll"
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
        >
          全选
        </el-checkbox>
        <el-button
            type="danger"
            size="small"
            @click="handleBatchOperation('delete')"
            v-if="selectedRows.length > 0"
            :icon="Delete"
        >
          批量删除
        </el-button>
      </div>

      <el-table
          :data="tableData.list"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @select-all="handleTableSelectAll"
          :loading="loading"
          :row-key="getRowKey"
          ref="tableRef"
      >
        <el-table-column
            type="selection"
            width="55"
        ></el-table-column>
        <el-table-column
            prop="id"
            label="商家ID"
            width="120"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="username"
            label="商家账号"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="name"
            label="商户名"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="image"
            label="商家照片"
            align="center"
            width="120"
        >
        <!-- 使用作用域插槽自定义单元格内容 -->
        <template #default="scope">
          <!-- 显示图片，设置合适的宽高 -->
          <el-image
              :src="scope.row.image"
          alt="商家照片"
          style="width: 80px; height: 60px; object-fit: cover"
          fit="cover"
          >
          <template #error>
            <div class="image-error">
              <el-icon>
                <PictureFilled/>
              </el-icon>
            </div>
          </template>
          </el-image>
        </template>
        </el-table-column>
        <el-table-column
            prop="phone"
            label="手机号"
            align="center"
        ></el-table-column>
        <el-table-column
            prop="intro"
            label="商家描述"
            align="center"
        ></el-table-column>
        <el-table-column
            label="操作"
            align="center"
            width="180"
        >
          <template #default="scope">
            <el-button
                size="small"
                @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="tableData.pageNum"
            v-model:page-size="tableData.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="tableData.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, toRefs, onMounted} from 'vue';
import {Plus, Search, Delete, Edit} from '@element-plus/icons-vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router';
import server from "../utils/request.js";
const dialogFormVisible = ref(false)
// 路由实例
const router = useRouter();
const form = reactive({
  username: '',
  password: '',
  name: ''
})
// 表格引用
const tableRef = ref();
const formLabelWidth = '140px'
// 状态管理
const state = reactive({
  // 加载状态
  loading: false,
  // 搜索表单
  searchForm: {
    keyword: '',
    status: ''
  },
  // 用户列表数据
  tableData: {
    list: [],
    // 分页信息
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  // 选中的行
  selectedRows: [],
  // 全选状态
  selectAll: false,
  // 半选状态
  isIndeterminate: false
});

const {loading, searchForm, tableData, selectedRows, selectAll, isIndeterminate} = toRefs(state);

// 获取行唯一键
const getRowKey = (row) => {
  return row.id;
};

// 获取数据
const fetchMerchantList = async () => {
  let {data: data} = await server.get(`/merchant/${tableData.value.pageNum}/${tableData.value.pageSize}`)
  Object.assign(tableData.value, data.data)
  // 每次获取新数据后清空选中状态
  selectedRows.value = [];
  selectAll.value = false;
  isIndeterminate.value = false;
};

// 条件查询
const handleSearch = async () => {
  let {data: data} = await server.get(`/merchant/search/${tableData.value.pageNum}/${tableData.value.pageSize}`, {
    params: {
      keyword: searchForm.value.keyword, // 搜索关键词（可为空）
      status: searchForm.value.status    // 状态筛选（可为空）
    }
  })
  Object.assign(tableData.value, data.data)
  // 每次获取新数据后清空选中状态
  selectedRows.value = [];
  selectAll.value = false;
  isIndeterminate.value = false;
};

// 初始化数据
onMounted(() => {
  fetchMerchantList()
})



// 重置筛选条件
const resetFilter = () => {
  searchForm.value = {
    keyword: '',
    status: '',
  };
  tableData.value.pageNum = 1;
  fetchMerchantList();
};

// 分页大小改变
const handleSizeChange = (val) => {
  tableData.value.pageSize = val;
  tableData.value.pageNum = 1;
  fetchMerchantList();
};

// 当前页改变
const handleCurrentChange = (val) => {
  tableData.value.pageNum = val;
  fetchMerchantList();
};

// 处理表格自带的全选功能
const handleTableSelectAll = (selection) => {
  selectedRows.value = selection;
  const isAllSelected = selection.length === tableData.value.list.length && tableData.value.list.length > 0;
  const isIndeterminate = selection.length > 0 && selection.length < tableData.value.list.length;

  selectAll.value = isAllSelected;
  isIndeterminate.value = isIndeterminate;
};

// 全选处理
const handleSelectAll = (val) => {
  if (val) {
    // 选中所有行
    tableData.value.list.forEach(row => {
      tableRef.value.toggleRowSelection(row, true);
    });
    selectedRows.value = [...tableData.value.list];
  } else {
    // 取消所有选中
    tableData.value.list.forEach(row => {
      tableRef.value.toggleRowSelection(row, false);
    });
    selectedRows.value = [];
  }
  isIndeterminate.value = false;
};

// 选择项改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
  const allSelected = rows.length === tableData.value.list.length && tableData.value.list.length > 0;
  const indeterminate = rows.length > 0 && rows.length < tableData.value.list.length;

  selectAll.value = allSelected;
  isIndeterminate.value = indeterminate;
};

// 查看用户详情
const handleView = (row) => {
  router.push(`/merchantDetail?id=${row.id}`);
};


// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确定要删除用户 ${row.username} 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
  ).then(async () => {
    // 模拟删除操作
    loading.value = true;
    //删除
    let {data: data} = await server.delete(`merchant/${row.id}`)
    if (data.code === 200) {
      ElMessage.success(data.data)
      await fetchMerchantList()
    }
  });
};

// 批量操作
const handleBatchOperation = (type) => {
  if (type === 'delete') {
    ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 个用户吗？此操作不可恢复！`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }
    ).then(() => {
      // 模拟批量删除
      loading.value = true;
      setTimeout(() => {
        const ids = selectedRows.value.map(row => row.id);
        tableData.value.list = tableData.value.list.filter(item => !ids.includes(item.id));
        tableData.value.total -= selectedRows.value.length;
        selectedRows.value = [];
        selectAll.value = false;
        isIndeterminate.value = false;
        ElMessage.success('批量删除成功');
        loading.value = false;
      }, 500);
    });
  } else if (type === 'export') {
    // 模拟导出
    ElMessage.success(`已导出 ${selectedRows.value.length} 条用户数据`);
  }
};

// 新增用户
const handleAddUser = async () => {
  let {data:data} = await server.post(`merchant/addMerchant`,form)
  if (data.code==200){
    ElMessage.success("添加成功")
    await fetchMerchantList()
    dialogFormVisible.value=false
  }else {
    ElMessage.error("添加失败")
    dialogFormVisible.value=false
  }
};
</script>

<style scoped>
.user-list-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.user-table-card {
  padding: 15px;
}

.table-actions {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .el-row {
    flex-wrap: wrap;
  }

  .el-col {
    margin-bottom: 10px;
  }

  .el-col:nth-child(1) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .el-col:nth-child(2),
  .el-col:nth-child(3),
  .el-col:nth-child(4) {
    flex: 0 0 50%;
    max-width: 50%;
  }

  .el-col:nth-child(5) {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .el-col:nth-child(2),
  .el-col:nth-child(3),
  .el-col:nth-child(4) {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .table-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>